package com.jzy.service.impl;

import com.jzy.constant.WebConstant;
import com.jzy.entity.Vo.LogVo;
import com.jzy.repository.LogRepository;
import com.jzy.service.ILogService;
import com.jzy.util.DateKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class LogServiceImpl implements ILogService {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogServiceImpl.class);


    @Resource
    private LogRepository logRepository;
    @Override
    public void insertLog(String action, String data, String ip, Integer authorId) {
        LogVo logs = new LogVo();
        logs.setAction(action);
        logs.setData(data);
        logs.setIp(ip);
        logs.setAuthorId(authorId);
        logs.setCreated(DateKit.getCurrentUnixTime());
        logRepository.saveAndFlush(logs);
    }

    @Override
    public List<LogVo> getLogs(int page, int limit) {
        LOGGER.debug("Enter getLogs method:page={},limit={}",page,limit);
        if (page <= 0) {
            page = 1;
        }
        if (limit < 1 || limit > WebConstant.MAX_POSTS) {
            limit = 10;
        }
        PageRequest pageRequest = getPageRequest(page, limit);
        return logRepository.findAll(pageRequest).getContent();
    }

    private PageRequest getPageRequest(int page, int limit) {
        ArrayList<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.DESC, "id"));
        Sort by = Sort.by(orders);
        return PageRequest.of(page-1, limit, by);
    }
}
